<?php

declare(strict_types=1);

namespace App\Goods\Model;

use App\Lib\Library\Helper;
use Mine\MineModel;
use PHPUnit\Runner\ErrorException;

/**
 * @property int $id 规格组ID
 * @property string $spec_name 规格组名称
 * @property int $store_id 商城ID
 * @property int $create_time 创建时间
 * @property int $update_time 更新时间
 */
class GoodsSpec extends MineModel
{
    protected ?string $dateFormat = 'U';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'goods_spec';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'spec_name', 'store_id', 'create_time', 'update_time'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'store_id' => 'integer', 'create_time' => 'integer', 'update_time' => 'integer'];


    public static function checkSpecData(array $specList)
    {
        $specNames = self::getArrayColumn($specList, 'spec_name');
        if (count($specList) != count(array_unique($specNames))) {
            throw new \ErrorException('很抱歉，不能存在重复的规格组');
        }
        foreach ($specList as $item) {
            $values = self::getArrayColumn($item['valueList'], 'spec_value');
            if (count($item['valueList']) != count(array_unique($values))) {
                throw new \ErrorException('很抱歉，不能存在重复的规格值');
            }
        }
    }

    /**
     * 规格组写入数据库并生成id
     * 此时的$specList是用户端传来的
     * @param array $specList
     * @param int|null $storeId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getNewSpecList(array $specList, int $storeId = null): array
    {
        // 规格组名称合集
        $names = self::getArrayColumn($specList, 'spec_name');

        // 获取到已存在的规格组
        $alreadyDataDb = static::getListByNames($names, $storeId);

        $alreadyData=$alreadyDataDb->isEmpty()?[]:$alreadyDataDb->toArray();

        // 遍历整理新的规格集
        foreach ($specList as $key => &$item) {
            $alreadyItem = Helper::getArrayItemByColumn($alreadyData, 'spec_name', $item['spec_name']);
            if (!empty($alreadyItem)) {
                // 规格名已存在的记录spec_id
                $item['spec_id'] = $alreadyItem['id'];
            } else {
                // 规格名不存在的新增记录
                $result = static::add($item, $storeId);
                $item['spec_id'] = $result['id'];
            }
            // 规格值写入数据库并生成id
            $item['valueList'] = GoodsSpecValue::getNewValueList((int)$item['spec_id'], $item['valueList'], $storeId);
        }
        return $specList;
    }

    private static function getListByNames(array $names, int $storeId = null)
    {
        return self::query()->whereIn('spec_name', $names)
            ->where('store_id', $storeId)
            ->get();
    }

    public static function getArrayColumn($source, $column): array
    {
        $columnArr = [];
        foreach ($source as $item) {
            isset($item[$column]) && $columnArr[] = $item[$column];
        }
        return $columnArr;
    }

    private static function add(array $item, int $storeId = null)
    {
        return self::create([
            'spec_name' => $item['spec_name'],
            'store_id' => empty($storeId) ? 0 : $storeId
        ]);
    }
}
